package activity

import (
	"context"
	"encoding/json"
	"fmt"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/utils/pointy"
	"mall/service/attachment/rpc/attachmentclient"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	enum "mall/service/backend/common/enum/promotion"
	"mall/service/backend/common/errorx"
	"mall/service/promotion/rpc/promotionclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePromotionActivityLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdatePromotionActivityLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePromotionActivityLogic {
	return &UpdatePromotionActivityLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdatePromotionActivityLogic) UpdatePromotionActivity(
	req *types.UpdatePromotionActivityReq,
) (*types.BaseMsgResp, error) {
	logx.Infof("UpdatePromotionActivityReq : %+v ", req)

	if len(req.Ids) > 0 {
		res, err := l.svcCtx.PromotionRpc.BackendUpdateActivity(l.ctx, &promotionclient.ActivityInfo{
			Status: req.Status,
			Ids:    req.Ids,
		})
		if err != nil {
			return nil, err
		}

		return &types.BaseMsgResp{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
		}, nil
	}

	if req.Id == nil || *req.Id == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "common.validationError"))
	}

	if req.Name != nil && len(strings.TrimSpace(*req.Name)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "promotion.activityNameRequired"))
	}

	adminId := jwt.GetBackendUserId(l.ctx)

	var skipMeta bool
	if req.SkipMeta != nil && *req.SkipMeta > 0 {
		skipMeta = true
	}
	var skipMedia bool
	if req.SkipMedia != nil && *req.SkipMedia > 0 {
		skipMedia = true
	}
	var skipContent bool
	if req.SkipContent != nil && *req.SkipContent > 0 {
		skipContent = true
	}

	var desc *string
	var descFiltered *string
	if !skipContent && req.Desc != nil && len(strings.TrimSpace(*req.Desc)) > 0 {
		parts := strings.Split(strings.TrimSpace(*req.Desc), globalkey.EditorSplitSymbol)
		if len(parts) > 0 {
			desc = pointy.GetPointer(parts[0])
		}
		if len(parts) > 1 {
			descFiltered = pointy.GetPointer(parts[1])
		}
	}

	var meta []*promotionclient.MetaInfo
	if !skipMeta && len(req.Meta) > 0 {
		for _, v := range req.Meta {
			meta = append(meta, &promotionclient.MetaInfo{
				Id:    v.Id,
				Key:   v.Key,
				Value: v.Value,
			})
		}
	}

	var allMedia []*promotionclient.MediaInfo
	newThumbMap := make(map[string]*types.MediaInfo)
	newMediaMap := make(map[string]*types.MediaInfo)
	var newMediaIds []string // 用于查询 attachmentRpc
	thumbnail := pointy.GetPointer(uint32(1))
	var newMedia []*promotionclient.MediaInfo
	var newAttachmentIds []string // 用于主动通知 attachmentRpc
	if !skipMedia {
		if len(req.AllMedia) > 0 { // 富文本所有图片
			for _, v := range req.AllMedia {
				allMedia = append(allMedia, &promotionclient.MediaInfo{
					Id:  v.Id,
					Url: v.Url,
				})
			}
		}

		if len(req.NewThumb) > 0 { // 封面图新图片
			for _, v := range req.NewThumb {
				if v.Id != nil && len(*v.Id) > 0 {
					if _, ok := newThumbMap[*v.Id]; !ok { // 忽略重复id
						newThumbMap[*v.Id] = v
						newMediaIds = append(newMediaIds, *v.Id)
					}
				} else {
					newMedia = append(newMedia, &promotionclient.MediaInfo{
						Uid:       v.Uid,
						Thumbnail: thumbnail,
						Order:     v.Order,
						Url:       v.Url,
						Name:      v.Name,
						MimeType:  v.MimeType,
						AltText:   v.AltText,
						MetaData:  v.MetaData,
					})
				}
			}
		}

		if len(req.NewMedia) > 0 { // 富文本新图片
			for _, v := range req.NewMedia {
				if v.Id != nil && len(*v.Id) > 0 {
					if _, ok := newMediaMap[*v.Id]; !ok { // 忽略重复id
						newMediaMap[*v.Id] = v
						newMediaIds = append(newMediaIds, *v.Id)
					}
				} else {
					newMedia = append(newMedia, &promotionclient.MediaInfo{
						Uid:      v.Uid,
						Order:    v.Order,
						Url:      v.Url,
						Name:     v.Name,
						MimeType: v.MimeType,
						AltText:  v.AltText,
						MetaData: v.MetaData,
					})
				}
			}
		}
	}

	if len(newMediaIds) > 0 {
		res, err := l.svcCtx.AttachmentRpc.BackendGetFileList(l.ctx, &attachmentclient.FileListReq{
			Ids: pointy.GetPointer(strings.Join(newMediaIds, ",")),
		})
		if err != nil {
			return nil, err
		}

		if len(res.List) > 0 {
			for _, v := range res.List {
				if v.Id != nil && len(*v.Id) > 0 {
					mediaId := *v.Id
					var url string
					if v.Url != nil && len(*v.Url) > 0 {
						url = fmt.Sprintf("%s%s", l.svcCtx.Config.NfsConf.StaticUrl, *v.Url)
					}
					if len(url) == 0 && v.Path != nil && len(*v.Path) > 0 {
						url = fmt.Sprintf("%s%s", l.svcCtx.Config.NfsConf.ProxyUrl, *v.Path)
					}

					if media, ok := newThumbMap[mediaId]; ok {
						newMedia = append(newMedia, &promotionclient.MediaInfo{
							Uid:       media.Uid,
							Id:        v.Id,
							Thumbnail: thumbnail,
							Order:     media.Order,
							Uri:       media.Url,
							Url:       pointy.GetPointer(url),
							Name:      media.Name,
							MimeType:  media.MimeType,
							AltText:   media.AltText,
							MetaData:  media.MetaData,
						})
						newAttachmentIds = append(newAttachmentIds, mediaId)
						continue
					}

					if media, ok := newMediaMap[mediaId]; ok {
						newMedia = append(newMedia, &promotionclient.MediaInfo{
							Uid:      media.Uid,
							Id:       v.Id,
							Order:    media.Order,
							Uri:      media.Url,
							Url:      pointy.GetPointer(url),
							Name:     media.Name,
							MimeType: media.MimeType,
							AltText:  media.AltText,
							MetaData: media.MetaData,
						})
						newAttachmentIds = append(newAttachmentIds, mediaId)
					}
				}
			}
		}
	}

	var groups []*promotionclient.ActivityRuleGroupInfo
	if len(req.Groups) > 0 {
		for _, v := range req.Groups {
			var rules []*promotionclient.ActivityRuleInfo
			if len(v.Rules) > 0 {
				for _, vv := range v.Rules {
					var regions *string
					if len(vv.Regions) > 0 {
						res, err := json.Marshal(vv.Regions)
						if err != nil {
							logx.Errorw("UpdatePromotionActivity ActivityRuleInfo json.Marshal err", logx.Field("detail", err.Error()))
							continue
						}

						regions = pointy.GetPointer(string(res))
					}

					rules = append(rules, &promotionclient.ActivityRuleInfo{
						Id:       vv.Id,
						Regions:  regions,
						RuleType: vv.RuleType,
						Mode:     vv.Mode,
						Value:    vv.Value,
					})
				}
			}

			groups = append(groups, &promotionclient.ActivityRuleGroupInfo{
				Id:        v.Id,
				Threshold: v.Threshold,
				Rules:     rules,
			})
		}
	} else {
		groups = []*promotionclient.ActivityRuleGroupInfo{{
			Threshold: req.ConditionValue,
			Rules: []*promotionclient.ActivityRuleInfo{{
				RuleType: req.Condition,
				Mode:     req.DiscountMode,
				Value:    req.DiscountValue,
			}},
		}}
	}

	var startedAt *string
	var endedAt *string
	if len(req.TimeRange) == 2 {
		startedAt = pointy.GetPointer(req.TimeRange[0])
		endedAt = pointy.GetPointer(req.TimeRange[1])
	} else if req.StartedAt != nil && req.EndedAt != nil {
		startedAt = req.StartedAt
		endedAt = req.EndedAt
	}

	res, err := l.svcCtx.PromotionRpc.BackendUpdateActivity(l.ctx, &promotionclient.ActivityInfo{
		Id:           req.Id,
		Name:         req.Name,
		Slug:         req.Slug,
		Desc:         desc,
		FilteredDesc: descFiltered,
		ScopeType:    req.ScopeType,
		ActivityType: pointy.GetPointer(uint32(enum.PromotionActivityDiscount)),
		GroupMode:    req.Condition,
		GroupType:    pointy.GetPointer(uint32(enum.PromotionActivityRuleGroupOne)),

		MemberRestriction:     req.MemberRestriction,
		MutexType:             req.MutexType,
		TimesLimit:            req.TimesLimit,
		SeckillLimit:          req.SeckillLimit,
		SeckillCancelDuration: req.SeckillCancelDuration,
		SeckillNotifyDuration: req.SeckillNotifyDuration,
		PackageType:           req.PackageType,
		PackagePicId:          req.PackagePicId,
		PackagePicUrl:         req.PackagePicUrl,

		StartedAt: startedAt,
		EndedAt:   endedAt,
		Status:    req.Status,
		Groups:    groups,
		Meta:      meta,
		AllMedia:  allMedia,
		NewMedia:  newMedia,
		UpdatedBy: pointy.GetPointer(adminId),
	})
	if err != nil {
		return nil, err
	}

	if len(newAttachmentIds) > 0 {
		_, err = l.svcCtx.AttachmentRpc.CreateFileLog(l.ctx, &attachmentclient.CreateFileLogReq{
			FileIds:    newAttachmentIds,
			UserId:     pointy.GetPointer(strconv.FormatInt(int64(adminId), 10)),
			Put:        pointy.GetPointer(uint32(1)),
			Thumbnail:  pointy.GetPointer(uint32(1)),
			ObjectId:   req.Id,
			ObjectType: pointy.GetPointer(uint32(globalkey.AttachmentLogTypePromotionCoupon)),
		})
		if err != nil {
			logx.Errorw("UpdatePromotionActivity CreateFileLog err", logx.Field("detail", err.Error()))
		}
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}
